<?php

namespace App\Http\Middleware;

use App\Tools\JsonTools;
use App\Tools\RabbitmqTools;
use Closure;
use Illuminate\Http\Request;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitmqMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     * 中间件限流
     */
    public function handle(Request $request, Closure $next)
    {
        $newRabbitMq = (RabbitmqTools::getInstance())->connectRabbitMq();
        $channel=$newRabbitMq->channel();
        $data=[
            "data"=>[],
            "code"=>2002,
            "msg"=>"等会再试"
        ];
        try {
            $basicGet=$channel->basic_get("limit");
            if(empty($basicGet->body)){
                $channel->queue_declare("limit",false,true,false,false);
                $channel->exchange_declare("limitExchange","direct",false);
                $channel->queue_bind("limit","limitExchange","1");
                for ($i=1;$i<=10;$i++){
                    $msg = new AMQPMessage($i);
                    $channel->basic_publish($msg,"limitExchange","1");
                }
                $channel->close();
                $newRabbitMq->close();
                return response()->json($data);
            }else{
                $channel->basic_qos(0,1,false);
                $channel->basic_nack($basicGet->getDeliveryTag());
                $channel->close();
                $newRabbitMq->close();
                return $next($request);
            }
        }catch (\Exception $exception){
            return response()->json([],2001,"等会消费");
        }

    }
}
